package com.xuan.common.core.domain;

import com.xuan.common.core.enums.ResultCode;
import lombok.Data;

@Data
public class R<T> {

    /**
     * 业务状态码
     */
    private Integer code;

    /**
     * 数据对象
     */
    private T data;

    /**
     * 消息内容
     */
    private String msg;

    private R (){}


    /**
     *  成功的返回结果
     * @return
     * @param <T>
     */
    public static <T> R<T> ok() {
        return assembleResult(null, ResultCode.SUCCESS);
    }

    public static <T> R<T> ok(T data) {
        return assembleResult(data, ResultCode.SUCCESS);
    }

    public static <T> R<T> ok(T data, String message) {
        return assembleResult(data, ResultCode.SUCCESS.getCode(), message);
    }

    /**
     *  失败的返回结果
     * @return
     * @param <T>
     */
    public static <T> R<T> fail() {
        return assembleResult(null, ResultCode.FAILED);
    }

    public static <T> R<T> fail(ResultCode resultCode) {
        return assembleResult(null, resultCode);
    }

    public static <T> R<T> fail(String message) {
        return assembleResult(null, ResultCode.FAILED.getCode(), message);
    }

    public static <T> R<T> fail(String message, int code) {
        return assembleResult(null, code, message);
    }

    public static <T> R<T> fail(String message, ResultCode resultCode) {
        return assembleResult(null, resultCode.getCode(), message);
    }


    /**
     *  组装返回结果
     * @param data
     * @param resultCode
     * @return
     * @param <T>
     */
    private static <T> R<T> assembleResult(T data, ResultCode resultCode) {
        R<T> r = new R<>();
        r.setCode(resultCode.getCode());
        r.setData(data);
        r.setMsg(resultCode.getMessage());
        return r;
    }

    private static <T> R<T> assembleResult(T data, int code, String message) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setData(data);
        r.setMsg(message);
        return r;
    }

}
